import axios from 'axios';

// 创建axios实例
export const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 可以在这里添加认证token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  },
);

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    // 统一错误处理
    if (error.response?.status === 401) {
      // 处理未授权
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  },
);

// API接口类型定义
export interface ContactFormData {
  name: string;
  email: string;
  message: string;
}

// API方法
export const contactAPI = {
  submit: (data: ContactFormData) => api.post('/contact', data),
};

// 其他API方法可以在这里添加
export const userAPI = {
  profile: () => api.get('/user/profile'),
  update: (data: any) => api.put('/user/profile', data),
};
